package com.fzg.common.tool;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 图片验证码工具类
 * @author fzg
 */
@Slf4j
@Service
public class ImageCodeTool {

    public static void main(String[] args) {
        Map<String, Object> imageCode = getImageCode();
        log.info(imageCode.get("imageCodeKey").toString());
        log.info(imageCode.get("imageCodeBase64").toString());
        String base64 = imageCode.get("imageCodeBase64").toString();
        String filePath = "C:\\Users\\Asus\\Desktop\\temp";
        String res = base64ToJpg(filePath, base64);
        log.info(res);
    }


    /**
     * 图片验证码缓存器
     */
    public static TimedCache<String, String> imageCodeCache = CacheUtil.newTimedCache(6000000);

    /**
     * 获得图片验证码
     * @return imageCodeKey、imageCodeBase64
     */
    public static Map<String, Object> getImageCode() {
        //启动定时器，没1秒清理一次
        imageCodeCache.schedulePrune(10000000);

        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        //将数据存储到缓存器中
        String imageCodeKey = IdUtil.simpleUUID();
        String imageCodeBase64 = circleCaptcha.getImageBase64Data();
        imageCodeCache.put(imageCodeKey, circleCaptcha.getCode());
        //返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("imageCodeKey", imageCodeKey);

        result.put("imageCodeBase64", imageCodeBase64);
        log.info(circleCaptcha.getCode());
        return result;
    }

    /**
     * 校验图片验证码
     * @param imageCodeKey 验证码秘钥
     * @param imageCode 验证码
     * @return boolean
     */
    public static boolean imageCodeCheck(String imageCodeKey, String imageCode) {
        String code = imageCodeCache.get(imageCodeKey);
        if(code == null) {
            return false;
        }
        else {
            return code.equals(imageCode);
        }
    }


    /**
     * base64转为图片
     * @param path
     * 文件路径：到文件夹即可，代码里会在文件夹里生成对应的jpg文件
     * @param base64 参数：base64编码
     * @return String
     */
    public static String base64ToJpg(String path,String base64){
        // 判断文件路径是否存在
        File filePath = new File(path);
        if (!filePath.exists()){
            filePath.mkdirs();
        }
        // 创建文件
        String jpgFile = path + "\\" + UUID.randomUUID() + ".jpg";
        File file = new File(jpgFile);
        boolean jpgFileExist = false;
        try {
            jpgFileExist = file.createNewFile();
            log.info("jpg文件创建成功");
        } catch (IOException e) {
            log.info("jpg文件创建失败");
            e.printStackTrace();
        }
        if (jpgFileExist){
            // 解密
            Base64.Decoder decoder = Base64.getDecoder();
            // 去掉base64前缀 data:image/jpeg;base64,
            base64 = base64.substring(base64.indexOf(",", 1) + 1);
            byte[] b = decoder.decode(base64);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 保存图片
            try {
                FileOutputStream out = new FileOutputStream(jpgFile);
                out.write(b);
                out.flush();
                out.close();
                // 写入成功返回文件路径
                return jpgFile;
            } catch (FileNotFoundException e) {
                log.info("文件未找到");
                e.printStackTrace();
            } catch (IOException e) {
                log.info("写入失败");
                e.printStackTrace();
            }
        }
        return "文件不存在";
    }


    /**
     * java 通过url下载图片保存到本地
     * @param urlString 图片链接地址
     * @param imgName 图片名称
     * @param path 图片要保存的路径
     * @throws Exception 异常
     */
    public static void download(String urlString, String imgName, String path) throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        String filename = path + "\\" + imgName + ".jpg";  //本地路径及图片名称
        File file = new File(filename);
        FileOutputStream os = new FileOutputStream(file, true);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // System.out.println(imgName);
        // 完毕，关闭所有链接
        os.close();
        is.close();
    }

}
